import CodeMirror from "codemirror";
import javascriptHint from "./javascript";
import groovyHint from "./groovy";

const javascriptHintTransfered = javascriptHint.map((item) => {
  // if (typeof item === "string") {
  //   return {
  //     displayText: item,
  //     text: item,
  //   };
  // }
  // return {
  //   displayText: item.displayText || item.label,
  //   text: item.text || item.insertText,
  // };
  const { insertText } = item;
  const newInsertText = insertText.replace(
    /\${\d+:(\w+)}/g,
    (all, target) => target
  );
  return {
    text: newInsertText,
    displayText: newInsertText,
  };
});

const languageHints = {
  java: groovyHint,
  groovy: groovyHint,
  js: javascriptHintTransfered,
  javascript: javascriptHintTransfered,
};

class CodeMirrorHint {
  /**
   * @param  {...any} args arg[0]为CodeMirror实例
   * @returns
   */
  static init(...args) {
    args[1] && console.log("args[1] =", args[1]);

    const cm = args[0];
    const language = cm?.options.mode;
    if (!language) return;

    const targetHint = languageHints[language];
    if (!targetHint) return;

    var cursor = cm.getCursor(),
      line = cm.getLine(cursor.line);
    var start = cursor.ch,
      end = cursor.ch;
    while (start && /\w/.test(line.charAt(start - 1))) --start;
    while (end < line.length && /\w/.test(line.charAt(end))) ++end;
    const word = line.slice(start, end).toLowerCase();
    const userHint = targetHint.filter((item) => {
      const key = item.displayText;
      return key.startsWith(word);
    });
    const defaultHint = CodeMirror.hint.javascript(cm, {}).list;
    const hints = userHint.concat(defaultHint);
    return {
      list: hints,
      from: CodeMirror.Pos(cursor.line, start),
      to: CodeMirror.Pos(cursor.line, end),
    };
  }
}

export default CodeMirrorHint;
